package com.swpu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.swpu.exception.BusinessException;
import com.swpu.result.ResultCode;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author 宋建博
 * @date 2023/6/7
 */

public class TokenUtil {

    private static final String ISSUER = "签发者";

    public static String generateToken(String userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, 30);
        return JWT.create().withKeyId(userId).withIssuer(ISSUER).withExpiresAt(calendar.getTime()).sign(algorithm);
    }

    public static String generateRefreshToken(String userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR, 2);
        return JWT.create().withKeyId(userId).withIssuer(ISSUER).withExpiresAt(calendar.getTime()).sign(algorithm);
    }

    public static String verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return (jwt.getKeyId());
        } catch (TokenExpiredException e) {
            throw new BusinessException(ResultCode.TOKEN_INVALID);
        }
        catch (Exception e) {
//            throw new BusinessException(ResultCode.ACCESS_UNAUTHORIZED);
        }

        return null;
    }

}
